// KaoQingManagement.tsx
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import styles from './KaoQingManagement.module.css';
import { io, Socket } from 'socket.io-client';

interface AttendanceRecord {
  id: number;
  studentId: string;
  studentName: string;
  className: string;
  date: string;
  coursePeriod: number;
  courseName: string;
  status: 'present' | 'absent' | 'late' | 'leave';
  teacher: string;
  createdAt?: string;
  updatedAt?: string;
  leaveImage?: string;
  isLateNight?: boolean;
}

interface StudentStat {
  studentId: string;
  studentName: string;
  className: string;
  totalCount: number;
  presentCount: number;
  absentCount: number;
  lateCount: number;
  leaveCount: number;
  attendanceRate: number;
}

interface Student {
  id: string;
  name: string;
  className: string;
  studentId?: string;
}

interface CourseSchedule {
  period: number;
  time: string;
  name: string;
}

const KaoQingManagement: React.FC = () => {
  const { t } = useTranslation('attendance');
  const [attendanceData, setAttendanceData] = useState<AttendanceRecord[]>([]);
  const [filteredData, setFilteredData] = useState<AttendanceRecord[]>([]);
  const [studentStats, setStudentStats] = useState<StudentStat[]>([]);
  const [loading, setLoading] = useState(true);
  // 初始化时设置为当天日期，默认只显示当天的记录
  const today = new Date().toISOString().split('T')[0];
  const [filters, setFilters] = useState({
    date: today, // 默认显示今天的记录
    className: '',
    status: '',
    studentName: '',
    coursePeriod: ''
  });
  const [selectedPeriod, setSelectedPeriod] = useState<number | null>(null);
  const [selectedClass, setSelectedClass] = useState<string>('');
  const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [isAdding, setIsAdding] = useState(false);
  const [showClassSelection, setShowClassSelection] = useState(false);

  // 班级点名相关状态
  const [classAttendanceModal, setClassAttendanceModal] = useState(false);
  const [currentClassStudents, setCurrentClassStudents] = useState<Student[]>([]);
  const [classAttendanceData, setClassAttendanceData] = useState<{[key: string]: string}>({});
  const [leaveImages, setLeaveImages] = useState<{[key: string]: File | null}>({});

  // 班级详情模态框相关状态
  const [classDetailModal, setClassDetailModal] = useState(false);
  const [selectedClassDetail, setSelectedClassDetail] = useState<{
    className: string;
    date: string;
    coursePeriod: number;
    records: AttendanceRecord[];
  } | null>(null);

  // 从后端获取的数据
  const [courseSchedule, setCourseSchedule] = useState<CourseSchedule[]>([]);
  const [students, setStudents] = useState<Student[]>([]);
  const [classList, setClassList] = useState<string[]>([]);
  const [teacherList, setTeacherList] = useState<string[]>([]);
  const [courseList, setCourseList] = useState<string[]>([]);
  const [lastUpdated, setLastUpdated] = useState<string>(new Date().toLocaleString());
  
  // Socket.IO连接引用
  const socketRef = useRef<Socket | null>(null);

  // 新记录表单数据
  const [newRecord, setNewRecord] = useState({
    studentId: '',
    studentName: '',
    className: '',
    date: new Date().toISOString().split('T')[0],
    coursePeriod: 1,
    courseName: '',
    status: 'present' as 'present' | 'absent' | 'late' | 'leave',
    teacher: ''
  });

  // API 基础URL
  const API_BASE = 'http://localhost:3001/api';

  // 从后端加载数据
  useEffect(() => {
    loadAllData();
    
    // 初始化Socket.IO连接
    if (!socketRef.current) {
      try {
        // 使用与API_BASE相同的基础URL配置Socket.IO连接
        // 根据API_BASE生成WebSocket URL
        const wsUrl = API_BASE.replace('http://', 'ws://').replace('/api', '');
        const socket = io(wsUrl, {
          autoConnect: true,
          reconnection: true,
          reconnectionAttempts: 5,
          reconnectionDelay: 1000
        });
        
        socketRef.current = socket;
        
        // 连接成功
        socket.on('connect', () => {
          console.log('WebSocket连接成功');
          // 加入考勤管理房间
          socket.emit('join-attendance-room', { userId: 'admin' });
        });
        
        // 连接错误处理
        socket.on('connect_error', (error) => {
          console.error('WebSocket连接错误:', error.message);
        });
        
        // 监听考勤记录创建事件
        socket.on('attendance:created', (data) => {
          console.log('收到新的考勤记录:', data);
          setAttendanceData(prev => [...prev, data]);
          setLastUpdated(new Date().toLocaleString());
          // 重新加载统计数据
          const loadStats = async () => {
            try {
              const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
              if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                setStudentStats(statsData);
              }
            } catch (error) {
              console.error('加载统计数据失败:', error);
            }
          };
          loadStats();
        });
        
        // 批量操作事件处理
        socket.on('attendance:batch-updated', (data) => {
          console.log('考勤记录批量更新:', data);
          setAttendanceData(prev => {
            const updated = [...prev];
            data.forEach((record: AttendanceRecord) => {
              const index = updated.findIndex(r => r.id === record.id);
              if (index !== -1) {
                updated[index] = record;
              } else {
                updated.push(record);
              }
            });
            return updated;
          });
          setLastUpdated(new Date().toLocaleString());
          // 重新加载统计数据
          const loadStats = async () => {
            try {
              const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
              if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                setStudentStats(statsData);
              }
            } catch (error) {
              console.error('加载统计数据失败:', error);
            }
          };
          loadStats();
        });
        
        // 监听考勤记录更新事件
        socket.on('attendance:updated', (data) => {
          console.log('考勤记录已更新:', data);
          setAttendanceData(prev => prev.map(record => 
            record.id === data.id ? data : record
          ));
          setLastUpdated(new Date().toLocaleString());
          // 重新加载统计数据
          const loadStats = async () => {
            try {
              const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
              if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                setStudentStats(statsData);
              }
            } catch (error) {
              console.error('加载统计数据失败:', error);
            }
          };
          loadStats();
        });
        
        // 监听考勤记录实时更新事件
        socket.on('attendance:realtime-updated', (data) => {
          console.log('考勤记录实时更新:', data);
          setAttendanceData(prev => prev.map(record => 
            record.id === data.id ? data : record
          ));
          setLastUpdated(new Date().toLocaleString());
          // 重新加载统计数据
          const loadStats = async () => {
            try {
              const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
              if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                setStudentStats(statsData);
              }
            } catch (error) {
              console.error('加载统计数据失败:', error);
            }
          };
          loadStats();
        });
        
        // 监听考勤记录删除事件
        socket.on('attendance:deleted', (data) => {
          console.log('考勤记录已删除:', data);
          setAttendanceData(prev => prev.filter(record => record.id !== data.id));
          setLastUpdated(new Date().toLocaleString());
          // 重新加载统计数据
          const loadStats = async () => {
            try {
              const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
              if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                setStudentStats(statsData);
              }
            } catch (error) {
              console.error('加载统计数据失败:', error);
            }
          };
          loadStats();
        });
        
        // 监听批量创建事件
        socket.on('attendance:batch-created', (data) => {
          console.log('批量创建考勤记录:', data);
          if (data.records && Array.isArray(data.records)) {
            setAttendanceData(prev => [...prev, ...data.records]);
            setLastUpdated(new Date().toLocaleString());
            // 重新加载统计数据
            const loadStats = async () => {
              try {
                const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
                if (statsResponse.ok) {
                  const statsData = await statsResponse.json();
                  setStudentStats(statsData);
                }
              } catch (error) {
                console.error('加载统计数据失败:', error);
              }
            };
            loadStats();
          }
        });
        
        // 监听批量更新事件
        socket.on('attendance:batch-updated', (data) => {
          console.log('批量更新考勤记录:', data);
          // 重新加载所有数据以确保一致性
          loadAllData();
          setLastUpdated(new Date().toLocaleString());
        });
        
        // 监听班级考勤创建事件
        socket.on('attendance:class-created', (data) => {
          console.log('班级考勤记录已创建:', data);
          if (data.createdRecords && Array.isArray(data.createdRecords)) {
            setAttendanceData(prev => [...prev, ...data.createdRecords]);
            setLastUpdated(new Date().toLocaleString());
            // 重新加载统计数据
            const loadStats = async () => {
              try {
                const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
                if (statsResponse.ok) {
                  const statsData = await statsResponse.json();
                  setStudentStats(statsData);
                }
              } catch (error) {
                console.error('加载统计数据失败:', error);
              }
            };
            loadStats();
          }
        });
        
        // 连接错误
        socket.on('connect_error', (error) => {
          console.error('WebSocket连接错误:', error);
        });
        
        // 断开连接
        socket.on('disconnect', (reason) => {
          console.log('WebSocket连接断开:', reason);
        });
        
      } catch (error) {
        console.error('初始化WebSocket连接失败:', error);
      }
    }
    
    // 设置定时刷新课程时间表，以便实时更新当前课程
    const interval = setInterval(() => {
      loadAllData();
    }, 30000); // 每30秒刷新一次
    
    return () => {
      clearInterval(interval);
      // 组件卸载时关闭WebSocket连接
      if (socketRef.current) {
        socketRef.current.emit('leave-attendance-room');
        socketRef.current.disconnect();
        socketRef.current = null;
      }
    };
  }, []);
  
  // 组件卸载时关闭WebSocket连接
  useEffect(() => {
    return () => {
      if (socketRef.current) {
        socketRef.current.off('connect');
        socketRef.current.off('connect_error');
        socketRef.current.off('attendance:created');
        socketRef.current.off('attendance:updated');
        socketRef.current.off('attendance:realtime-updated');
        socketRef.current.off('attendance:deleted');
        socketRef.current.off('attendance:batch-updated');
        socketRef.current.emit('leave-attendance-room');
        socketRef.current.disconnect();
        socketRef.current = null;
      }
    };
  }, []);


  const loadAllData = async () => {
    try {
      setLoading(true);
      
      const [
        attendanceRes,
        statsRes,
        optionsRes,
        scheduleRes
      ] = await Promise.all([
        fetch(`${API_BASE}/attendance?page=1&pageSize=10000`), // 获取所有记录
        fetch(`${API_BASE}/attendance/stats`),
        fetch(`${API_BASE}/attendance/options`),
        fetch(`${API_BASE}/attendance/course-schedule`)
      ]);

      if (!attendanceRes.ok || !statsRes.ok || !optionsRes.ok || !scheduleRes.ok) {
        throw new Error('数据加载失败');
      }

      const attendanceData = await attendanceRes.json();
      const statsData = await statsRes.json();
      const optionsData = await optionsRes.json();
      const scheduleData = await scheduleRes.json();

      console.log('加载考勤数据:', attendanceData);
      console.log('考勤记录数量:', attendanceData.data?.length || 0);
      
      const allRecords = attendanceData.data || [];
      setAttendanceData(allRecords);
      
      // 默认只显示当天的记录（如果没有设置其他筛选条件）
      const today = new Date().toISOString().split('T')[0];
      if (!filters.date || filters.date === '') {
        // 如果筛选条件中没有日期，默认显示今天
        const todayRecords = allRecords.filter((item: AttendanceRecord) => item.date === today);
        setFilteredData(todayRecords);
      } else {
        // 如果有筛选条件，使用筛选逻辑（会由useEffect自动过滤）
        setFilteredData(allRecords);
      }
      setStudentStats(statsData);
      setStudents(optionsData.students || []);
      setClassList(optionsData.classes || []);
      setTeacherList(optionsData.teachers || []);
      setCourseList(optionsData.courses || []);
      setCourseSchedule(scheduleData);

    } catch (error) {
      console.error('加载数据失败:', error);
      alert('数据加载失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 过滤数据
  useEffect(() => {
    let result = [...attendanceData];
    
    console.log('开始过滤数据，总记录数:', result.length);
    console.log('筛选条件:', filters);
    console.log('selectedPeriod:', selectedPeriod);
    
    // 默认只显示当天的记录（如果没有设置日期筛选）
    const today = new Date().toISOString().split('T')[0];
    if (!filters.date || filters.date === '') {
      result = result.filter(item => item.date === today);
      console.log('默认筛选当天记录后:', result.length);
    } else {
      // 如果设置了日期，按设置的日期筛选
      result = result.filter(item => item.date === filters.date);
      console.log('按日期筛选后:', result.length);
    }
    
    // 如果三个关键筛选条件都存在（日期、班级、课程节次），则只显示当节课的记录
    const isFilteringCurrentClass = filters.date && filters.className && filters.coursePeriod;
    
    if (filters.className) {
      // 精确匹配班级名称，而不是包含
      result = result.filter(item => item.className && item.className === filters.className);
      console.log('按班级筛选后:', result.length);
    }
    
    if (filters.coursePeriod) {
      const periodNum = parseInt(filters.coursePeriod);
      result = result.filter(item => {
        // 确保类型匹配
        const itemPeriod = typeof item.coursePeriod === 'string' ? parseInt(item.coursePeriod) : item.coursePeriod;
        return itemPeriod === periodNum;
      });
      console.log('按课程节次筛选后:', result.length);
    }
    
    // 如果三个条件都存在，说明是要显示当节课的记录，不再进行其他筛选
    if (!isFilteringCurrentClass) {
      // 其他筛选条件（只在不是显示当节课时生效）
      if (filters.status) {
        result = result.filter(item => item.status === filters.status);
        console.log('按状态筛选后:', result.length);
      }
      
      if (filters.studentName) {
        result = result.filter(item => item.studentName && item.studentName.includes(filters.studentName));
        console.log('按姓名筛选后:', result.length);
      }
    }
    
    // 如果selectedPeriod不为null，也进行筛选（但提交后会被清空）
    if (selectedPeriod !== null) {
      result = result.filter(item => {
        const itemPeriod = typeof item.coursePeriod === 'string' ? parseInt(item.coursePeriod) : item.coursePeriod;
        return itemPeriod === selectedPeriod;
      });
      console.log('按selectedPeriod筛选后:', result.length);
    }
    
    console.log('最终过滤结果:', result.length, '条记录', isFilteringCurrentClass ? '(当节课记录)' : '');
    setFilteredData(result);
  }, [filters, attendanceData, selectedPeriod]);

  // 处理表单输入变化
  const handleInputChange = (field: string, value: string | number) => {
    setNewRecord(prev => ({
      ...prev,
      [field]: value
    }));

    if (field === 'studentId' && value) {
      const student = students.find(s => s.id === value);
      if (student) {
        setNewRecord(prev => ({
          ...prev,
          studentName: student.name,
          className: student.className
        }));
      }
    }

    if (field === 'coursePeriod' && typeof value === 'number') {
      setNewRecord(prev => ({
        ...prev,
        courseName: courseList[value - 1] || '通用课程'
      }));
    }
  };

  // 添加新的考勤记录
  const handleAddRecord = async () => {
    if (!newRecord.studentId) {
      alert(t('pleaseSelectStudent'));
      return;
    }

    try {
      const response = await fetch(`${API_BASE}/attendance`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newRecord)
      });

      if (!response.ok) {
        throw new Error('添加记录失败');
      }

      const addedRecord = await response.json();
      
      const updatedData = [...attendanceData, addedRecord];
      setAttendanceData(updatedData);
      
      const statsResponse = await fetch(`${API_BASE}/attendance/stats`);
      if (statsResponse.ok) {
        const statsData = await statsResponse.json();
        setStudentStats(statsData);
      }

      setNewRecord({
        studentId: '',
        studentName: '',
        className: '',
        date: new Date().toISOString().split('T')[0],
        coursePeriod: selectedPeriod || 1,
        courseName: courseList[(selectedPeriod || 1) - 1] || '通用课程',
        status: 'present',
        teacher: ''
      });

      setIsAdding(false);
      alert(t('addSuccess'));

    } catch (error) {
      console.error('添加记录失败:', error);
      alert(t('addFailed'));
    }
  };

  // 更新考勤状态
  const handleStatusChange = async (id: number, newStatus: AttendanceRecord['status']) => {
    try {
      const record = attendanceData.find(item => item.id === id);
      if (!record) return;

      const updatedRecord = {
        ...record,
        status: newStatus
      };

      const response = await fetch(`${API_BASE}/attendance/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updatedRecord)
      });

      if (!response.ok) {
        throw new Error('更新记录失败');
      }

      const result = await response.json();
      
      const updatedData = attendanceData.map(item => 
        item.id === id ? result : item
      );
      setAttendanceData(updatedData);

      // 如果模态框打开且包含该记录，更新模态框中的数据
      if (classDetailModal && selectedClassDetail) {
        const updatedRecords = selectedClassDetail.records.map(item =>
          item.id === id ? result : item
        );
        setSelectedClassDetail({
          ...selectedClassDetail,
          records: updatedRecords
        });
      }

    } catch (error) {
      console.error('更新记录失败:', error);
      alert(t('updateFailed'));
    }
  };

  // 删除考勤记录
  const handleDeleteRecord = async (id: number) => {
    if (!confirm(t('confirmDelete'))) return;

    try {
      const response = await fetch(`${API_BASE}/attendance/${id}`, {
        method: 'DELETE'
      });

      if (!response.ok) {
        throw new Error('删除记录失败');
      }

      const updatedData = attendanceData.filter(item => item.id !== id);
      setAttendanceData(updatedData);

      // 如果模态框打开且包含该记录，更新模态框中的数据
      if (classDetailModal && selectedClassDetail) {
        const updatedRecords = selectedClassDetail.records.filter(item => item.id !== id);
        if (updatedRecords.length === 0) {
          // 如果所有记录都被删除，关闭模态框
          closeClassDetail();
        } else {
          setSelectedClassDetail({
            ...selectedClassDetail,
            records: updatedRecords
          });
        }
      }

      alert(t('deleteSuccess'));

    } catch (error) {
      console.error('删除记录失败:', error);
      alert(t('deleteFailed'));
    }
  };

  // 处理班级点名
  const handleClassAttendance = (className: string) => {
    try {
      console.log('处理班级点名:', className);
      // 直接从已加载的学生数据中过滤出该班级的学生
      const classStudents = students.filter(student => student.className === className);
      
      if (classStudents.length === 0) {
        console.log('该班级暂无学生');
        alert(`班级 ${className} 暂无学生`);
        return;
      }
      
      console.log(`获取到 ${classStudents.length} 名学生`);
      setCurrentClassStudents(classStudents);
      
      // 初始化考勤状态
      const initialAttendance: {[key: string]: string} = {};
      classStudents.forEach((student: Student) => {
        initialAttendance[student.id] = 'present'; // 默认出勤
      });
      setClassAttendanceData(initialAttendance);
      // 重置请假条图片
      setLeaveImages({});
      // 打开点名弹窗
      setClassAttendanceModal(true);
    } catch (error) {
      console.error('获取班级学生失败:', error);
      alert(t('common:fetchError') || '获取班级学生失败');
    }
  };

  // 处理考勤状态变化
  const handleClassAttendanceChange = (studentId: string, status: string) => {
    setClassAttendanceData(prev => ({
      ...prev,
      [studentId]: status
    }));
  };

  // 处理请假条图片上传
  const handleLeaveImageChange = (studentId: string, file: File | null) => {
    setLeaveImages(prev => ({
      ...prev,
      [studentId]: file
    }));
  };

  // 提交班级考勤
  const submitClassAttendance = async () => {
    if (!selectedPeriod || !selectedClass || !selectedDate) {
      alert('请选择课程节次、班级和日期');
      return;
    }

    // 检查该班级该日期该课程节次是否已有记录
    try {
      const checkResponse = await fetch(
        `${API_BASE}/attendance/class-period?className=${encodeURIComponent(selectedClass)}&date=${selectedDate}&coursePeriod=${selectedPeriod}`
      );
      
      if (checkResponse.ok) {
        const checkData = await checkResponse.json();
        if (checkData.data && checkData.data.length > 0) {
          const confirmUpdate = confirm(
            `该班级在 ${selectedDate} 的第${selectedPeriod}节课已有 ${checkData.data.length} 条记录。\n` +
            `如果继续提交，将删除旧记录并创建新记录。是否继续？`
          );
          if (!confirmUpdate) {
            return;
          }
          
          // 删除旧记录
          for (const oldRecord of checkData.data) {
            await fetch(`${API_BASE}/attendance/${oldRecord.id}`, {
              method: 'DELETE'
            });
          }
        }
      }
    } catch (error) {
      console.error('检查现有记录失败:', error);
      // 继续执行，不阻止提交
    }

    const now = new Date();
    const currentHour = now.getHours();
    
    // 检查是否超过晚上9点
    if (currentHour >= 21) {
      if (!confirm('当前时间已超过晚上9点，点名将会产生扣款。是否继续？')) {
        return;
      }
    }
    
    try {
      const attendanceRecords: AttendanceRecord[] = [];
      
      for (const student of currentClassStudents) {
        const status = classAttendanceData[student.id] || 'present';
        let leaveImageUrl = '';
        
        // 如果是请假状态，需要上传请假条
        if (status === 'leave') {
          const imageFile = leaveImages[student.id];
          if (!imageFile) {
            alert(`${student.name} 选择请假状态，请上传请假条图片`);
            return;
          }
          
          // 上传请假条图片
          const formData = new FormData();
          formData.append('leaveImage', imageFile);
          formData.append('studentId', student.id);
          
          const uploadResponse = await fetch(`${API_BASE}/attendance/leave-image`, {
            method: 'POST',
            body: formData
          });
          
          if (uploadResponse.ok) {
            const uploadResult = await uploadResponse.json();
            leaveImageUrl = uploadResult.imageUrl;
          } else {
            alert(`${student.name} 请假条上传失败`);
            return;
          }
        }
        
        // 创建考勤记录
        const record: Partial<AttendanceRecord> & {
          studentId: string;
          studentName: string;
          className: string;
          date: string;
          coursePeriod: number;
          courseName: string;
          status: string;
          teacher: string;
          leaveImage: string;
          isLateNight: boolean;
        } = {
          studentId: student.studentId || student.id,
          studentName: student.name,
          className: student.className,
          date: selectedDate,
          coursePeriod: selectedPeriod,
          courseName: courseList[selectedPeriod - 1] || '通用课程',
          status: status as 'present' | 'absent' | 'late' | 'leave',
          teacher: teacherList[0] || '',
          leaveImage: leaveImageUrl,
          isLateNight: currentHour >= 21 // 标记是否为晚上9点后点名
        };
        
        attendanceRecords.push(record as AttendanceRecord);
      }
      
      console.log('准备提交考勤记录:', attendanceRecords);
      
      // 批量提交考勤记录
      const response = await fetch(`${API_BASE}/attendance/batch`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ records: attendanceRecords })
      });
      
      console.log('提交响应状态:', response.status, response.ok);
      
      if (response.ok) {
        const result = await response.json();
        console.log('提交成功，响应数据:', result);
        
        // 保存筛选条件（在清空状态之前）
        const filterDate = selectedDate;
        const filterClassName = selectedClass;
        const filterCoursePeriod = selectedPeriod;
        
        alert(`成功保存 ${attendanceRecords.length} 条考勤记录`);
        setClassAttendanceModal(false);
        setShowClassSelection(false);
        
        // 重新加载数据，确保新记录显示在表格中
        await loadAllData();
        
        // 等待一下确保数据已加载
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 设置筛选条件，只显示刚才提交的记录（精确匹配日期、班级、课程节次）
        const newFilters = {
          date: filterDate, // 只显示当前日期
          className: filterClassName, // 只显示当前班级
          status: '', // 不筛选状态，显示所有状态
          studentName: '', // 不筛选姓名
          coursePeriod: filterCoursePeriod ? filterCoursePeriod.toString() : '' // 只显示当前课程节次
        };
        console.log('设置筛选条件（只显示本次提交的记录）:', newFilters);
        setFilters(newFilters);
        
        // 自动打开班级详情模态框，显示刚提交的记录
        // 等待数据加载完成后打开
        setTimeout(async () => {
          // 重新加载数据后获取最新的记录
          await loadAllData();
          // 稍等一下确保状态已更新，然后从最新的数据中筛选
          setTimeout(() => {
            // 使用loadAllData后的最新数据
            const today = filterDate;
            const classRecords = attendanceData.filter(item => {
              const itemPeriod = typeof item.coursePeriod === 'string' ? parseInt(item.coursePeriod) : item.coursePeriod;
              const filterPeriod = typeof filterCoursePeriod === 'number' ? filterCoursePeriod : parseInt(filterCoursePeriod);
              return item.className === filterClassName &&
                     item.date === today &&
                     itemPeriod === filterPeriod;
            });
            if (classRecords.length > 0) {
              openClassDetail(filterClassName, filterDate, filterCoursePeriod, classRecords);
            }
          }, 150);
        }, 300);
        
        // 确保selectedPeriod也被清空，避免双重筛选
        setSelectedPeriod(null);
        
        // 清空选择状态（在设置筛选条件之后）
        setSelectedClass('');
        setCurrentClassStudents([]);
        setClassAttendanceData({});
        setLeaveImages({});
      } else {
        const errorData = await response.json();
        throw new Error(errorData.error || '提交失败');
      }
      
    } catch (error) {
      console.error('提交班级考勤失败:', error);
      alert('提交失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 打开添加记录表单
  const openAddForm = () => {
    setIsAdding(true);
    setNewRecord({
      studentId: '',
      studentName: '',
      className: '',
      date: new Date().toISOString().split('T')[0],
      coursePeriod: selectedPeriod || 1,
      courseName: courseList[(selectedPeriod || 1) - 1] || '通用课程',
      status: 'present',
      teacher: teacherList[0] || ''
    });
  };

  // 关闭添加记录表单
  const closeAddForm = () => {
    setIsAdding(false);
  };

  const handleFilterChange = (key: string, value: string) => {
    setFilters(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // 打开班级详情模态框
  const openClassDetail = (className: string, date: string, coursePeriod: number, records: AttendanceRecord[]) => {
    setSelectedClassDetail({
      className,
      date,
      coursePeriod,
      records
    });
    setClassDetailModal(true);
  };

  // 关闭班级详情模态框
  const closeClassDetail = () => {
    setClassDetailModal(false);
    setSelectedClassDetail(null);
  };

  // 按班级分组数据
  const groupedByClass = () => {
    const groups: {[key: string]: AttendanceRecord[]} = {};
    filteredData.forEach(record => {
      const key = `${record.className}-${record.date}-${record.coursePeriod}`;
      if (!groups[key]) {
        groups[key] = [];
      }
      groups[key].push(record);
    });
    return groups;
  };

  // 获取班级统计信息
  const getClassStats = (records: AttendanceRecord[]) => {
    const presentCount = records.filter(r => r.status === 'present').length;
    const lateCount = records.filter(r => r.status === 'late').length;
    const absentCount = records.filter(r => r.status === 'absent').length;
    const leaveCount = records.filter(r => r.status === 'leave').length;
    return { presentCount, lateCount, absentCount, leaveCount, total: records.length };
  };

  const clearCourseSelection = () => {
    setSelectedPeriod(null);
  };

  const getStatusText = (status: AttendanceRecord['status']): string => {
    const statusMap = {
      present: t('present'),
      absent: t('absent'),
      late: t('late'),
      leave: t('leave')
    };
    return statusMap[status];
  };

  const getStatusColor = (status: AttendanceRecord['status']) => {
    const colorMap = {
      present: styles.statusPresent,
      absent: styles.statusAbsent,
      late: styles.statusLate,
      leave: styles.statusLeave
    };
    return colorMap[status];
  };

  const getRateColor = (rate: number) => {
    if (rate >= 90) return styles.rateExcellent;
    if (rate >= 80) return styles.rateGood;
    if (rate >= 60) return styles.rateFair;
    return styles.ratePoor;
  };

  const exportToExcel = () => {
    const headers = [t('studentId'), t('name'), t('className'), t('date'), t('coursePeriod'), t('courseName'), t('status'), t('teacher')];
    const csvContent = [
      headers.join(','),
      ...filteredData.map(item => [
        item.studentId,
        item.studentName,
        item.className,
        item.date,
        `${t('periodPrefix')}${item.coursePeriod}${t('periodSuffix')}`,
        item.courseName,
        getStatusText(item.status),
        item.teacher
      ].join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `考勤记录_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 获取当前显示的课程信息
  const getCurrentCourseInfo = () => {
    if (selectedPeriod !== null) {
      const course = courseSchedule.find(c => c.period === selectedPeriod);
      return course ? `${t('periodPrefix')}${course.period}${t('periodSuffix')} (${course.time}) - ${courseList[selectedPeriod - 1] || t('unknownCourse')}` : t('allCourses');
    }
    return t('allCourses');
  };

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <div className={styles.loadingContent}>
          <div className={styles.loadingSpinner}></div>
          <div className={styles.loadingText}>加载中...</div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      {/* 页面头部 */}
      <div className={styles.header}>
        <div className={styles.headerContent}>
          <div>
            <h1 className={styles.title}>{t('title')}</h1>
            {selectedPeriod !== null && (
              <div className={styles.currentCourse}>
                <span className={styles.currentCourseLabel}>{t('currentViewing')}</span>
                <span className={styles.currentCourseValue}>
                  {getCurrentCourseInfo()}
                </span>
                <button 
                  className={styles.clearSelectionButton}
                  onClick={clearCourseSelection}
                >
                  {t('viewAllCourses')}
                </button>
              </div>
            )}
          </div>
          <div className={styles.headerActions}>
            <button 
              className={styles.primaryButton}
              onClick={openAddForm}
            >
              <svg className={styles.buttonIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              {t('addRecord')}
            </button>
            <button 
              className={styles.secondaryButton}
              onClick={exportToExcel}
            >
              <svg className={styles.buttonIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              {t('exportExcel')}
            </button>
          </div>
        </div>
      </div>

      {/* 添加记录模态框 */}
      {isAdding && (
        <div className={styles.modalOverlay}>
          <div className={styles.modal}>
            <div className={styles.modalHeader}>
              <h3 className={styles.modalTitle}>{t('addRecord')}</h3>
              <button 
                className={styles.modalClose}
                onClick={closeAddForm}
              >
                ×
              </button>
            </div>
            
            <div className={styles.modalBody}>
              <div className={styles.formGrid}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>{t('student')}</label>
                  <select
                    value={newRecord.studentId}
                    onChange={(e) => handleInputChange('studentId', e.target.value)}
                    className={styles.select}
                    required
                  >
                    <option value="">{t('pleaseSelectStudent')}</option>
                    {students.map(student => (
                      <option key={student.id} value={student.id}>
                        {student.name} ({student.id}) - {student.className}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className={styles.formGroup}>
                  <label className={styles.label}>{t('date')}</label>
                  <input
                    type="date"
                    value={newRecord.date}
                    onChange={(e) => handleInputChange('date', e.target.value)}
                    className={styles.input}
                    required
                  />
                </div>
              </div>

              <div className={styles.formGrid}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>{t('coursePeriod')}</label>
                  <select
                    value={newRecord.coursePeriod}
                    onChange={(e) => handleInputChange('coursePeriod', parseInt(e.target.value))}
                    className={styles.select}
                    required
                  >
                    {courseSchedule.map(course => (
                      <option key={course.period} value={course.period}>
                        {t('periodPrefix')}{course.period}{t('periodSuffix')} ({course.time})
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className={styles.formGroup}>
                  <label className={styles.label}>{t('courseName')}</label>
                  <input
                    type="text"
                    value={newRecord.courseName}
                    onChange={(e) => handleInputChange('courseName', e.target.value)}
                    className={styles.input}
                    required
                  />
                </div>
              </div>

              <div className={styles.formGrid}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>{t('status')}</label>
                  <select
                    value={newRecord.status}
                    onChange={(e) => handleInputChange('status', e.target.value)}
                    className={styles.select}
                    required
                  >
                    <option value="present">{t('present')}</option>
                    <option value="late">{t('late')}</option>
                    <option value="absent">{t('absent')}</option>
                    <option value="leave">{t('leave')}</option>
                  </select>
                </div>
                
                <div className={styles.formGroup}>
                  <label className={styles.label}>{t('teacher')}</label>
                  <select
                    value={newRecord.teacher}
                    onChange={(e) => handleInputChange('teacher', e.target.value)}
                    className={styles.select}
                    required
                  >
                    <option value="">{t('pleaseSelectTeacher')}</option>
                    {teacherList.map(teacher => (
                      <option key={teacher} value={teacher}>{teacher}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className={styles.preview}>
                <h4 className={styles.previewTitle}>
                  <svg className={styles.previewIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {t('recordPreview')}
                </h4>
                <div className={styles.previewGrid}>
                  <div><span className={styles.previewLabel}>{t('previewStudent')}</span>{newRecord.studentName || t('notSelected')}</div>
                  <div><span className={styles.previewLabel}>{t('previewClass')}</span>{newRecord.className || t('notSelected')}</div>
                  <div><span className={styles.previewLabel}>{t('previewStatus')}</span>
                    <span className={`${styles.statusBadge} ${getStatusColor(newRecord.status)}`}>
                      {getStatusText(newRecord.status)}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            
            <div className={styles.modalFooter}>
              <button 
                className={styles.cancelButton}
                onClick={closeAddForm}
              >
                {t('cancel')}
              </button>
              <button 
                className={styles.confirmButton}
                onClick={handleAddRecord}
              >
                {t('save')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 班级点名模态框 */}
      {classAttendanceModal && selectedPeriod !== null && (
        <div className={styles.modalOverlay}>
          <div className={styles.modal} style={{ maxWidth: '800px' }}>
            <div className={styles.modalHeader}>
              <h3 className={styles.modalTitle}>
                {t('classAttendance')} - {currentClassStudents[0]?.className || selectedClass}
                <span style={{ marginLeft: '10px', fontSize: '14px', fontWeight: 'normal', color: '#64748b' }}>
                  ({t('periodPrefix')}{selectedPeriod}{t('periodSuffix')} - {selectedDate})
                </span>
              </h3>
              <button 
                className={styles.modalClose}
                onClick={() => {
                  setClassAttendanceModal(false);
                  setCurrentClassStudents([]);
                  setClassAttendanceData({});
                  setLeaveImages({});
                }}
              >
                ×
              </button>
            </div>
            
            <div className={styles.modalBody}>
              <div className={styles.classAttendanceGrid}>
                {currentClassStudents.map(student => (
                  <div key={student.id} className={styles.studentAttendanceItem}>
                    <div className={styles.studentInfo}>
                      <span className={styles.studentName}>{student.name}</span>
                      <span className={styles.studentId}>({student.id})</span>
                    </div>
                    
                    <div className={styles.attendanceActions}>
                      <select
                        value={classAttendanceData[student.id] || 'present'}
                        onChange={(e) => handleClassAttendanceChange(student.id, e.target.value)}
                        className={styles.statusSelect}
                      >
                        <option value="present">{t('present')}</option>
                        <option value="late">{t('late')}</option>
                        <option value="absent">{t('absent')}</option>
                        <option value="leave">{t('leave')}</option>
                      </select>
                      
                      {classAttendanceData[student.id] === 'leave' && (
                        <div className={styles.leaveImageUpload}>
                          <label className={styles.uploadLabel}>
                            <input
                              type="file"
                              accept="image/*"
                              onChange={(e) => handleLeaveImageChange(student.id, e.target.files?.[0] || null)}
                              className={styles.fileInput}
                            />
                            {leaveImages[student.id] ? t('selected') : t('uploadLeaveImage')}
                          </label>
                          {leaveImages[student.id] && (
                            <span className={styles.fileName}>
                              {leaveImages[student.id]?.name}
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            
            <div className={styles.modalFooter}>
              <button 
                className={styles.cancelButton}
                onClick={() => setClassAttendanceModal(false)}
              >
                {t('cancel')}
              </button>
              <button 
                className={styles.confirmButton}
                onClick={submitClassAttendance}
              >
                {t('submitAttendance')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 课程选择 */}
      <div className={styles.section}>
        <div className={styles.sectionHeader}>
          <h3 className={styles.sectionTitle}>{t('selectCoursePeriod')}</h3>
          {selectedPeriod !== null && (
            <div className={styles.selectionInfo}>
              {t('selectedPeriod')}{selectedPeriod}{t('period')} {
                filteredData.filter(item => {
                  const today = new Date().toISOString().split('T')[0];
                  const itemPeriod = typeof item.coursePeriod === 'string' ? parseInt(item.coursePeriod) : item.coursePeriod;
                  return itemPeriod === selectedPeriod && item.date === today;
                }).length
              }{t('records')}
            </div>
          )}
        </div>
        <div className={styles.courseGrid}>
          {courseSchedule.map(course => (
            <button
              key={course.period}
              className={`${styles.courseCard} ${
                selectedPeriod === course.period ? styles.courseCardSelected : ''
              }`}
              onClick={() => {
                setSelectedPeriod(course.period);
                setShowClassSelection(true);
                setSelectedClass('');
                setCurrentClassStudents([]);
                setClassAttendanceData({});
              }}
            >
              <div className={styles.courseContent}>
                  <div className={styles.coursePeriod}>{t('selectedPeriod')}{course.period}{t('period')}</div>
                <div className={styles.courseTime}>{course.time}</div>
                <div className={styles.courseName}>
                  {courseList[course.period - 1] || t('genericCourse')}
                </div>
                <div className={styles.courseCount}>
                  {attendanceData.filter(item => {
                    const today = new Date().toISOString().split('T')[0];
                    const itemPeriod = typeof item.coursePeriod === 'string' ? parseInt(item.coursePeriod) : item.coursePeriod;
                    return itemPeriod === course.period && item.date === today;
                  }).length} {t('record')}
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* 班级选择区域（点击课程节次后显示） */}
      {selectedPeriod !== null && showClassSelection && (
        <div className={styles.section}>
          <div className={styles.sectionHeader}>
            <h3 className={styles.sectionTitle}>
              {t('periodPrefix')}{selectedPeriod}{t('periodSuffix')} - 选择班级进行考勤
            </h3>
            <button
              className={styles.cancelButton}
              onClick={() => {
                setShowClassSelection(false);
                setSelectedPeriod(null);
                setSelectedClass('');
                setCurrentClassStudents([]);
                setClassAttendanceData({});
              }}
              style={{ padding: '8px 16px', marginLeft: 'auto' }}
            >
              取消
            </button>
          </div>
          <div className={styles.filterGrid}>
            <div className={styles.filterGroup}>
              <label className={styles.label}>日期</label>
              <input
                type="date"
                value={selectedDate}
                onChange={(e) => setSelectedDate(e.target.value)}
                className={styles.input}
              />
            </div>
            <div className={styles.filterGroup}>
              <label className={styles.label}>选择班级</label>
              <select
                value={selectedClass}
                onChange={(e) => {
                  const className = e.target.value;
                  setSelectedClass(className);
                  if (className) {
                    // 获取该班级的学生列表
                    const classStudents = students.filter(student => student.className === className);
                    if (classStudents.length === 0) {
                      alert(`班级 ${className} 暂无学生`);
                      return;
                    }
                    setCurrentClassStudents(classStudents);
                    // 初始化考勤状态
                    const initialAttendance: {[key: string]: string} = {};
                    classStudents.forEach((student: Student) => {
                      initialAttendance[student.id] = 'present'; // 默认出勤
                    });
                    setClassAttendanceData(initialAttendance);
                    setLeaveImages({});
                    // 打开点名弹窗
                    setClassAttendanceModal(true);
                  }
                }}
                className={styles.select}
              >
                <option value="">请选择班级</option>
                {classList.map(className => (
                  <option key={className} value={className}>{className}</option>
                ))}
              </select>
            </div>
          </div>
        </div>
      )}

      {/* 筛选条件 */}
      <div className={styles.section}>
        <h3 className={styles.sectionTitle}>筛选条件</h3>
        <div className={styles.filterGrid}>
          <div className={styles.filterGroup}>
            <label className={styles.label}>日期</label>
            <input
              type="date"
              value={filters.date}
              onChange={(e) => handleFilterChange('date', e.target.value)}
              className={styles.input}
            />
          </div>
          
          <div className={styles.filterGroup}>
            <label className={styles.label}>班级</label>
            <select
              value={filters.className}
              onChange={(e) => handleFilterChange('className', e.target.value)}
              className={styles.select}
            >
              <option value="">{t('allClasses')}</option>
              {classList.map(className => (
                <option key={className} value={className}>{className}</option>
              ))}
            </select>
          </div>
          
          <div className={styles.filterGroup}>
            <label className={styles.label}>{t('status')}</label>
            <select
              value={filters.status}
              onChange={(e) => handleFilterChange('status', e.target.value)}
              className={styles.select}
            >
              <option value="">{t('all')}</option>
              <option value="present">{t('present')}</option>
              <option value="absent">{t('absent')}</option>
              <option value="late">{t('late')}</option>
              <option value="leave">{t('leave')}</option>
            </select>
          </div>
          
          <div className={styles.filterGroup}>
            <label className={styles.label}>{t('studentName')}</label>
            <input
              type="text"
              placeholder={t('pleaseInput') + t('studentName')}
              value={filters.studentName}
              onChange={(e) => handleFilterChange('studentName', e.target.value)}
              className={styles.input}
            />
          </div>

          <div className={styles.filterGroup}>
            <label className={styles.label}>课程节次</label>
            <select
              value={filters.coursePeriod}
              onChange={(e) => handleFilterChange('coursePeriod', e.target.value)}
              className={styles.select}
            >
              <option value="">{t('all')}</option>
              {courseSchedule.map(course => (
                <option key={course.period} value={course.period}>
                  {t('periodPrefix')}{course.period}{t('periodSuffix')}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

     {/* 班级网格 */}
<div className={styles.section}>
  <h3 className={styles.sectionTitle}>
    <svg className={styles.sectionIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
    </svg>
    班级列表
  </h3>
  
  <div className={styles.classGrid}>
    {classList.map(className => (
      <div
        key={className}
        className={styles.classCard}
        onClick={() => handleClassAttendance(className)}
      >
        <div className={styles.classContent}>
          <div className={styles.className}>{className}</div>
          <div className={styles.classInfo}>
            <div className={styles.studentCount}>
              {students.filter(s => s.className === className).length}{t('students')}
            </div>
            <div className={styles.attendanceCount}>
              {attendanceData.filter(item => item.className === className).length} {t('records')}
            </div>
          </div>
          <div className={styles.classAction}>
            <span>{t('clickToAttendance')}</span>
            <svg className={styles.arrowIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </div>
        </div>
      </div>
    ))}
  </div>
</div>

      {/* 考勤记录表格（按班级分组） */}
      <div className={styles.section}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
          <h3 className={styles.sectionTitle}>
            <svg className={styles.sectionIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            考勤详细记录
          </h3>
          <div style={{ fontSize: '0.85rem', color: '#64748b' }}>
            最后更新: {lastUpdated}
          </div>
        </div>
        <div className={styles.tableContainer}>
          <table className={styles.table}>
            <thead className={styles.tableHead}>
              <tr>
                <th className={styles.tableHeader} style={{ width: '40px' }}></th>
                <th className={styles.tableHeader}>{t('className')}</th>
                <th className={styles.tableHeader}>{t('date')}</th>
                <th className={styles.tableHeader}>{t('coursePeriod')}</th>
                <th className={styles.tableHeader}>出勤统计</th>
                <th className={styles.tableHeader} style={{ width: '120px' }}>操作</th>
              </tr>
            </thead>
            <tbody className={styles.tableBody}>
              {filteredData.length === 0 ? (
                <tr>
                  <td colSpan={6} className={styles.emptyState}>
                    <svg className={styles.emptyIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <h3 className={styles.emptyTitle}>没有找到记录</h3>
                    <p className={styles.emptyDescription}>尝试调整筛选条件或添加新记录</p>
                  </td>
                </tr>
              ) : (
                Object.entries(groupedByClass()).map(([key, records]) => {
                  const firstRecord = records[0];
                  const className = firstRecord.className;
                  const stats = getClassStats(records);
                  
                  return (
                    <React.Fragment key={key}>
                      {/* 班级汇总行 */}
                      <tr 
                        className={styles.tableRow}
                        style={{ 
                          backgroundColor: '#f8fafc',
                          fontWeight: 500
                        }}
                      >
                        <td className={styles.tableCell} style={{ width: '40px' }}>
                          {/* 占位，保持布局一致 */}
                        </td>
                        <td className={`${styles.tableCell} ${styles.tableCellBold}`}>
                          {className}
                        </td>
                        <td className={styles.tableCell}>{firstRecord.date}</td>
                        <td className={styles.tableCell}>
                          {t('periodPrefix')}{firstRecord.coursePeriod}{t('periodSuffix')}
                        </td>
                        <td className={styles.tableCell}>
                          <div style={{ display: 'flex', gap: '8px', fontSize: '12px' }}>
                            <span style={{ color: '#52c41a' }}>出勤: {stats.presentCount}</span>
                            <span style={{ color: '#faad14' }}>迟到: {stats.lateCount}</span>
                            <span style={{ color: '#f5222d' }}>缺勤: {stats.absentCount}</span>
                            <span style={{ color: '#1890ff' }}>请假: {stats.leaveCount}</span>
                            <span style={{ color: '#666' }}>总计: {stats.total}</span>
                          </div>
                        </td>
                        <td className={styles.tableCell}>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              openClassDetail(className, firstRecord.date, firstRecord.coursePeriod, records);
                            }}
                            style={{ 
                              padding: '6px 16px', 
                              fontSize: '14px',
                              border: '1px solid #d1d5db',
                              borderRadius: '4px',
                              backgroundColor: '#fff',
                              color: '#374151',
                              cursor: 'pointer',
                              transition: 'all 0.2s'
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.backgroundColor = '#f9fafb';
                              e.currentTarget.style.borderColor = '#9ca3af';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.backgroundColor = '#fff';
                              e.currentTarget.style.borderColor = '#d1d5db';
                            }}
                          >
                            详情
                          </button>
                        </td>
                      </tr>
                    </React.Fragment>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
        <div className={styles.tableFooter}>
          <div className={styles.recordCount}>
            {t('totalRecords')} <span className={styles.recordCountNumber}>{filteredData.length}</span> {t('records')}
          </div>
          <div className={styles.lastUpdated}>
            {t('lastUpdated')}: {new Date().toLocaleString('zh-CN')}
          </div>
        </div>
      </div>

      {/* 班级详情模态框 */}
      {classDetailModal && selectedClassDetail && (
        <div className={styles.modalOverlay} onClick={closeClassDetail}>
          <div className={styles.modal} style={{ maxWidth: '900px', maxHeight: '80vh' }} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <h3 className={styles.modalTitle}>
                班级详情 - {selectedClassDetail.className}
                <span style={{ marginLeft: '10px', fontSize: '14px', fontWeight: 'normal', color: '#64748b' }}>
                  ({selectedClassDetail.date} - {t('periodPrefix')}{selectedClassDetail.coursePeriod}{t('periodSuffix')})
                </span>
              </h3>
              <button 
                className={styles.modalClose}
                onClick={closeClassDetail}
              >
                ×
              </button>
            </div>
            
            <div className={styles.modalBody} style={{ maxHeight: '60vh', overflowY: 'auto' }}>
              <div className={styles.tableContainer}>
                <table className={styles.table}>
                  <thead className={styles.tableHead}>
                    <tr>
                      <th className={styles.tableHeader}>{t('studentId')}</th>
                      <th className={styles.tableHeader}>{t('name')}</th>
                      <th className={styles.tableHeader}>{t('courseName')}</th>
                      <th className={styles.tableHeader}>{t('teacher')}</th>
                      <th className={styles.tableHeader}>{t('status')}</th>
                      <th className={styles.tableHeader}>{t('operation')}</th>
                    </tr>
                  </thead>
                  <tbody className={styles.tableBody}>
                    {selectedClassDetail.records.map(record => (
                      <tr key={record.id} className={styles.tableRow}>
                        <td className={styles.tableCell}>{record.studentId}</td>
                        <td className={`${styles.tableCell} ${styles.tableCellBold}`}>{record.studentName}</td>
                        <td className={styles.tableCell}>{record.courseName}</td>
                        <td className={styles.tableCell}>{record.teacher}</td>
                        <td className={styles.tableCell}>
                          <span className={`${styles.statusBadge} ${getStatusColor(record.status)}`}>
                            {getStatusText(record.status)}
                          </span>
                        </td>
                        <td className={styles.tableCell}>
                          <div className={styles.actionGroup}>
                            <select
                              value={record.status}
                              onChange={(e) => handleStatusChange(record.id, e.target.value as AttendanceRecord['status'])}
                              className={styles.statusSelect}
                            >
                              <option value="present">{t('present')}</option>
                              <option value="late">{t('late')}</option>
                              <option value="absent">{t('absent')}</option>
                              <option value="leave">{t('leave')}</option>
                            </select>
                            <button
                              onClick={() => handleDeleteRecord(record.id)}
                              className={styles.deleteButton}
                            >
                              {t('delete')}
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
            
            <div className={styles.modalFooter}>
              <button 
                className={styles.confirmButton}
                onClick={closeClassDetail}
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default KaoQingManagement;